package com.store.app.activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.AppOpsManager;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.google.gson.Gson;
import com.google.zxing.WriterException;
import com.hyphenate.easeui.model.DBHelper_hy;
import com.hyphenate.easeui.model.recordBean_hy;
import com.hyphenate.easeui.widget.CircleImageView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.store.app.BaseActivity;
import com.store.app.ExitApplication;
import com.store.app.LocationApplication;
import com.store.app.MainActivity;
import com.store.app.R;
import com.store.app.adapter.Stores_ServiceAdapter;
import com.store.app.bean.BitmapBean;
import com.store.app.bean.ServiceUpdateBean;
import com.store.app.bean.StoresDetailsBean;
import com.store.app.bean.StoresPicBean;
import com.store.app.database.Database;
import com.store.app.database.DatabaseMethod;
import com.store.app.http.Stores;
import com.store.app.imlife.utils.ToastTools;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.stores.LocationService;
import com.store.app.stores.MultipartEntity;
import com.store.app.utils.SettingData;
import com.store.app.utils.Utils;
import com.store.app.utils.UtilsBitmap;
import com.yalantis.ucrop.CropUtils;
import com.yalantis.ucrop.UCrop;
import com.zxing.decoding.EncodingHandler;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
/**
 * 店铺页面
 */

public class StoresActivity extends BaseActivity implements View.OnClickListener, IOnHttpListener {


    private LinearLayout vista, service;
    //	private RelativeLayout vistaone;
    private RelativeLayout rl_zhezhao;
    private RelativeLayout rl_zhezhao2;
    private TextView site;
    private EditText desc_edit;

    private MapView mMapView = null;
    private BaiduMap mBaidumap;
    private String locationProvider, scope = "200米", demand = "0元", error, doc_id = "";
    private BitmapDescriptor bitmap;
    private Bitmap vistabitmap;            //拍照后拿到的图片
    private LocationClient locationClient = null;
    private LocationService locationService;

    private TextView phone, name, submit, personage_name;
    private Database database;
    private DatabaseMethod method;
    private ProgressDialog progressBar;
    private Stores_ServiceAdapter serviceAdapter;        //精准定位地址
    private boolean needSubmit = false;            //是否需要提交
    private String newDrawable = null;        //从服务器获取到的图片
    private static final int FLAG_CHOOSE_IMG = 5;
    private static final int FLAG_CHOOSE_PHONE = 6;
    private static final int FLAG_MODIFY_FINISH = 7;
    private static final int SHOW_PIC = 20;
    private static final int LOAD_PIC_FAIL = 21;
    private static String localTempImageFileName = "";
    //图片地址
    private String img_add = "";
    //经纬度
    private String s_latitude = "", s_longitude = "";
    private LinearLayout lin_erweima;

    private NetRequest netRequest;
    //数据库存储
    private DBHelper_hy db = null;
    private recordBean_hy rb = null;
    private Handler handler = new Handler() {
        @SuppressLint("NewApi")
        @Override
        public void handleMessage(Message msg) {// handler接收到消息后就会执行此方法
            super.handleMessage(msg);
            switch (msg.what) {

                case 2:
                    if (progressBar != null && progressBar.isShowing())
                        progressBar.dismiss();
                    Toast.makeText(StoresActivity.this, "请检查本地网络！",
                            Toast.LENGTH_SHORT).show();
                    break;
                case 3:
                    if (progressBar != null && progressBar.isShowing())
                        progressBar.dismiss();
                    Toast.makeText(StoresActivity.this, error,
                            Toast.LENGTH_SHORT).show();
                    break;
                case 4:
                    if (progressBar != null && progressBar.isShowing())
                        progressBar.dismiss();
                    Toast.makeText(StoresActivity.this, "提交成功",
                            Toast.LENGTH_SHORT).show();
                    finish();
                    break;
                case 9:
                    //从服务器获取到图片，显示
                    ImageLoader.getInstance().displayImage(newDrawable, imageView, new ImageLoadingListener() {

                        @Override
                        public void onLoadingStarted(String s, View view) {

                        }

                        @Override
                        public void onLoadingFailed(String s, View view, FailReason failReason) {

                        }

                        @Override
                        public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                            imageView.setVisibility(View.VISIBLE);
//							vistaone.setVisibility(View.GONE);
                            rl_zhezhao.setVisibility(View.VISIBLE);
                        }

                        @Override
                        public void onLoadingCancelled(String s, View view) {

                        }
                    });
//					imageView.setBackground(newDrawable);

                    break;

                case SHOW_PIC:
                    temBitmap = bitmapBean.getBitmap();
                    if (temBitmap == null) {
                        return;
                    }
                    if (tempIndex == 0) {
//                        iv_add_photo_one.setImageBitmap(temBitmap);
                        iv_head.setImageBitmap(temBitmap);

                    } else if (tempIndex == 1) {
                        imageView.setVisibility(View.VISIBLE);
                        imageView.setImageBitmap(temBitmap);
                        rl_zhezhao.setVisibility(View.VISIBLE);
                    } else if (tempIndex == 2) {
                        iv_room_one.setImageBitmap(temBitmap);
                    } else if (tempIndex == 3) {
                        iv_room_two.setImageBitmap(temBitmap);
                    } else if (tempIndex == 4) {
                        iv_room_three.setImageBitmap(temBitmap);
                    } else if (tempIndex == 5) {
                        iv_room_four.setImageBitmap(temBitmap);
                    }
                    break;
                case LOAD_PIC_FAIL:
                    ToastTools.show(StoresActivity.this, "上传图片失败！", Toast.LENGTH_SHORT);
                    break;
                default:
                    break;
            }
        }
    };
    private RelativeLayout rl_stores_name;
    private CircleImageView iv_head;                //头像
    private ImageView imageView;                    //街景图片
    private int chooseIndex = 0;        //记录选择图片的位置，0代表头像，1代表街景
    private int tempIndex = 0;
    private String docIdOne = "", docIdTwo = "", docIdRoomOne = "", docIdRoomTwo = "", docIdRoomThree = "", docIdRoomFour = "";  //街景图id跟头像id还有四张内景图
    private Bitmap temBitmap;  //临时存储图片
    private StoresDetailsBean storesDetailsBean;
    private ImageView iv_room_one;
    private ImageView iv_room_two;
    private ImageView iv_room_three;
    private ImageView iv_room_four;
    private List<StoresPicBean> storesPicBeansList = new ArrayList<>();
    private BitmapBean bitmapBean;
    private LinearLayout ll_helper;
    private Resources resources;
    private ImageView iv_wifi;
    private TextView tv_wifi;
    private ImageView iv_wc;
    private TextView tv_wc;
    private ImageView iv_hot_water;
    private TextView tv_hot_water;
    private ImageView iv_battery;
    private TextView tv_battery;
    private ImageView iv_tools;
    private TextView tv_tools;
    private ImageView iv_express;
    private TextView tv_express;
    private ImageView iv_lock;
    private TextView tv_lock;
    private ImageView iv_dredge;
    private TextView tv_dredge;
    private ImageView iv_maintain;
    private TextView tv_maintain;
    private ImageView iv_return;
    private TextView tv_return;
    private ImageView iv_insurance;
    private TextView tv_insurance;
    private ImageView iv_other;
    private TextView tv_other;
    private List<Integer> tempList=new ArrayList<>();//记录服务要提交的数据

    private void initData() {
        netRequest = new NetRequest(this);
        //如果有路径，则去获取url
        if (!TextUtils.isEmpty(Stores.neighbor_pic_path)) {
            Log.v("zyl", "Stores.neighbor_pic_path:" + Stores.neighbor_pic_path);
            needSubmit = false;
            // new get_url("street_images", Stores.neighbor_pic_path, "").start();
        }
        initPageDate();
        netRequest.requestQueryStoresInfo(2);
    }

    private void initPageDate() {
        name.setText(Stores.stores_name);
        site.setText(Stores.address);
        personage_name.setText(Stores.contact_person);
        phone.setText(Stores.contact_tel);
        if (!TextUtils.isEmpty(Stores.store_desc)) {
            desc_edit.setText(Stores.store_desc);
        }
        s_latitude = Stores.latitude;
        s_longitude = Stores.longitude;
        if (!TextUtils.isEmpty(s_latitude) && !TextUtils.isEmpty(s_longitude) && !s_latitude.equals("4.9E-324")
                && !s_longitude.equals("4.9E-324")) {
            try {
                setbaidumapjxdu(Double.parseDouble(s_latitude), Double.parseDouble(s_longitude));
                mMapView.setVisibility(View.VISIBLE);
            } catch (Exception e) {

            }
        }
    }

    private void initView() {
         resources = getResources();
        imageView = (ImageView) findViewById(R.id.vistaimg);
        name = (TextView) findViewById(R.id.name);
        site = (TextView) findViewById(R.id.site);
        personage_name = (TextView) findViewById(R.id.personage_name);
        phone = (TextView) findViewById(R.id.phone);
        desc_edit = (EditText) findViewById(R.id.et_about);
        findViewById(R.id.retreat).setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                finish();
            }
        });
        ll_helper = (LinearLayout) findViewById(R.id.ll_my_helper);
        ll_helper.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent2 = new Intent(StoresActivity.this, ContactHelperActivity.class);
                startActivity(intent2);
            }
        });
        findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                update();
            }
        });
//		vistaone = (RelativeLayout) findViewById(R.id.vistaone);
        rl_zhezhao = (RelativeLayout) findViewById(R.id.rl_zhezhao);
        rl_zhezhao2 = (RelativeLayout) findViewById(R.id.rl_zhezhao2);
        rl_zhezhao2.setOnClickListener(this);
        vista = (LinearLayout) findViewById(R.id.vista);
        vista.setOnClickListener(this);
        submit = (TextView) findViewById(R.id.submit);
        submit.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                update();
            }
        });

//        service = (LinearLayout) findViewById(R.id.store_service);
//        service.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                MobclickAgent.onEvent(StoresActivity.this, "004");
//                Intent intent = new Intent();
//                intent.setClass(StoresActivity.this, ServiceActivity.class);
//                if (storesDetailsBean == null) {
//                    netRequest.requestQueryStoresInfo(2);
//                } else {
//                    intent.putExtra("activity_service", storesDetailsBean.getActivity_servcie());
//                    startActivity(intent);
//                }
//
//            }
//        });

        //地图
        mMapView = (MapView) findViewById(R.id.bmapview);
        mBaidumap = mMapView.getMap();
        // 构建Marker图标
        bitmap = BitmapDescriptorFactory.fromResource(R.drawable.local);
        locationService = ((LocationApplication) getApplication()).locationService;
        // 获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
        locationService.registerListener(mListener);
        locationService.setLocationOption(locationService.getDefaultLocationClientOption());
        mMapView.showZoomControls(false);


        storesPicBeansList.add(0, new StoresPicBean());
        storesPicBeansList.add(1, new StoresPicBean());
        storesPicBeansList.add(2, new StoresPicBean());
        storesPicBeansList.add(3, new StoresPicBean());

        rl_stores_name = (RelativeLayout) findViewById(R.id.rl_stores_name);
        rl_stores_name.setOnClickListener(this);
        iv_head = (CircleImageView) findViewById(R.id.iv_head);
        iv_room_one = (ImageView) findViewById(R.id.iv_room_one);
        iv_room_one.setOnClickListener(this);
        iv_room_two = (ImageView) findViewById(R.id.iv_room_two);
        iv_room_two.setOnClickListener(this);
        iv_room_three = (ImageView) findViewById(R.id.iv_room_three);
        iv_room_three.setOnClickListener(this);
        iv_room_four = (ImageView) findViewById(R.id.iv_room_four);
        iv_room_four.setOnClickListener(this);
        lin_erweima = (LinearLayout) findViewById(R.id.public_ll_right);
        lin_erweima.setOnClickListener(this);

        iv_wifi = (ImageView) findViewById(R.id.iv_wifi);
        tv_wifi = (TextView) findViewById(R.id.tv_wifi);
        iv_wc = (ImageView) findViewById(R.id.iv_wc);
        tv_wc = (TextView) findViewById(R.id.tv_wc);
        iv_hot_water = (ImageView) findViewById(R.id.iv_hot_water);
        tv_hot_water = (TextView) findViewById(R.id.tv_hot_water);
        iv_battery = (ImageView) findViewById(R.id.iv_battery);
        tv_battery = (TextView) findViewById(R.id.tv_battery);
        iv_tools = (ImageView) findViewById(R.id.iv_tools);
        tv_tools = (TextView) findViewById(R.id.tv_tools);
        iv_express = (ImageView) findViewById(R.id.iv_express);
        tv_express = (TextView) findViewById(R.id.tv_express);
        iv_lock = (ImageView) findViewById(R.id.iv_lock);
        tv_lock = (TextView) findViewById(R.id.tv_lock);
        iv_dredge = (ImageView) findViewById(R.id.iv_dredge);
        tv_dredge = (TextView) findViewById(R.id.tv_dredge);
        iv_maintain = (ImageView) findViewById(R.id.iv_maintain);
        tv_maintain = (TextView) findViewById(R.id.tv_maintain);
        iv_return = (ImageView) findViewById(R.id.iv_return);
        tv_return = (TextView) findViewById(R.id.tv_return);
        iv_insurance = (ImageView) findViewById(R.id.iv_insurance);
        tv_insurance = (TextView) findViewById(R.id.tv_insurance);
        iv_other = (ImageView) findViewById(R.id.iv_other);
        tv_other = (TextView) findViewById(R.id.tv_other);

        iv_wifi.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                if (tempList.contains(1)) {
                    iv_wifi.setBackgroundResource(R.drawable.wifi_bigicongray);
                    tv_wifi.setTextColor(resources.getColor(R.color.service_text_color_normal));
                    deleteelement(1);
                } else {
                    iv_wifi.setBackgroundResource(R.drawable.wifi_bigiconorg);
                    tv_wifi.setTextColor(resources.getColor(R.color.service_text_color));
                    tempList.add(1);
                }
            }
        });

        iv_wc.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {

                if (tempList.contains(2)) {
                    iv_wc.setBackgroundResource(R.drawable.wc_bigicongray);
                    tv_wc.setTextColor(resources.getColor(R.color.service_text_color_normal));
                    deleteelement(2);
                } else {
                    iv_wc.setBackgroundResource(R.drawable.wc_bigiconorg);
                    tv_wc.setTextColor(resources.getColor(R.color.service_text_color));
                    tempList.add(2);
                }
            }
        });

        //热水
        iv_hot_water.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {

                if (tempList.contains(3)) {
                    iv_hot_water.setBackgroundResource(R.drawable.hot2_bigicongray);
                    tv_hot_water.setTextColor(resources.getColor(R.color.service_text_color_normal));
                    deleteelement(3);
                } else {
                    iv_hot_water.setBackgroundResource(R.drawable.hot2_bigiconorg);
                    tv_hot_water.setTextColor(resources.getColor(R.color.service_text_color));
                    tempList.add(3);
                }
            }
        });

        iv_battery.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                if (tempList.contains(6)) {
                    iv_battery.setBackgroundResource(R.drawable.dian_bigicongray);
                    tv_battery.setTextColor(resources.getColor(R.color.service_text_color_normal));
                    deleteelement(6);
                } else {
                    iv_battery.setBackgroundResource(R.drawable.dian_bigiconorg);
                    tv_battery.setTextColor(resources.getColor(R.color.service_text_color));
                    tempList.add(6);
                }
            }
        });

        iv_tools.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                if (tempList.contains(21)) {
                    iv_tools.setBackgroundResource(R.drawable.tool_bigicongray);
                    tv_tools.setTextColor(resources.getColor(R.color.service_text_color_normal));
                    deleteelement(21);
                } else {
                    iv_tools.setBackgroundResource(R.drawable.tool_bigiconorg);
                    tv_tools.setTextColor(resources.getColor(R.color.service_text_color));
                    tempList.add(21);
                }
            }
        });
        //快递收发
        iv_express.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                if (tempList.contains(8)) {
                    iv_express.setBackgroundResource(R.drawable.ex_bigicongray);
                    tv_express.setTextColor(resources.getColor(R.color.service_text_color_normal));
                    deleteelement(8);
                } else {
                    iv_express.setBackgroundResource(R.drawable.ex_bigiconorg);
                    tv_express.setTextColor(resources.getColor(R.color.service_text_color));
                    tempList.add(8);
                }
            }
        });
        //便民开锁
        iv_lock.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                if (tempList.contains(14)) {
                    iv_lock.setBackgroundResource(R.drawable.suo_bigicongray);
                    tv_lock.setTextColor(resources.getColor(R.color.service_text_color_normal));
                    deleteelement(14);
                } else {
                    iv_lock.setBackgroundResource(R.drawable.suo_bigiconorg);
                    tv_lock.setTextColor(resources.getColor(R.color.service_text_color));
                    tempList.add(14);
                }
            }
        });
        //管道疏通
        iv_dredge.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                if (tempList.contains(16)) {
                    iv_dredge.setBackgroundResource(R.drawable.tong_bigicongray);
                    tv_dredge.setTextColor(resources.getColor(R.color.service_text_color_normal));
                    deleteelement(16);
                } else {
                    iv_dredge.setBackgroundResource(R.drawable.tong_bigiconorg);
                    tv_dredge.setTextColor(resources.getColor(R.color.service_text_color));
                    tempList.add(16);
                }
            }
        });
        //家电维修
        iv_maintain.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                if (tempList.contains(20)) {
                    iv_maintain.setBackgroundResource(R.drawable.wx_bigicongray);
                    tv_maintain.setTextColor(resources.getColor(R.color.service_text_color_normal));
                    deleteelement(20);
                } else {
                    iv_maintain.setBackgroundResource(R.drawable.wx_bigiconorg);
                    tv_maintain.setTextColor(resources.getColor(R.color.service_text_color));
                    tempList.add(20);
                }
            }
        });
        //二手回收
        iv_return.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                if (tempList.contains(26)) {
                    iv_return.setBackgroundResource(R.drawable.pic_return_gray);
                    tv_return.setTextColor(resources.getColor(R.color.service_text_color_normal));
                    deleteelement(26);
                } else {
                    iv_return.setBackgroundResource(R.drawable.pic_return_red);
                    tv_return.setTextColor(resources.getColor(R.color.service_text_color));
                    tempList.add(26);
                }
            }
        });
        //保险代理
        iv_insurance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (tempList.contains(27)) {
                    iv_insurance.setBackgroundResource(R.drawable.pic_baoxian_gray);
                    tv_insurance.setTextColor(resources.getColor(R.color.service_text_color_normal));
                    deleteelement(27);
                } else {
                    iv_insurance.setBackgroundResource(R.drawable.pic_baoxian_red);
                    tv_insurance.setTextColor(resources.getColor(R.color.service_text_color));
                    tempList.add(27);
                }
            }
        });
        //其他
        iv_other.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (tempList.contains(28)) {
                    iv_other.setBackgroundResource(R.drawable.pic_other_gray);
                    tv_other.setTextColor(resources.getColor(R.color.service_text_color_normal));
                    deleteelement(28);
                } else {
                    iv_other.setBackgroundResource(R.drawable.pic_other_red);
                    tv_other.setTextColor(resources.getColor(R.color.service_text_color));
                    tempList.add(28);
                }
            }
        });
    }

    /**
     * 删除取消的服务
     * @param integer
     */
    private void deleteelement(Integer integer) {
        for (int i = tempList.size() - 1; i >= 0; i--) {
            Integer str = tempList.get(i);
            if (str == integer) {
                tempList.remove(str);
            }
        }
    }
    /**
     * 初始化服务状态
     */
    private void initServiceState() {
        tempList = new ArrayList<>();
        String activity_service = storesDetailsBean.getActivity_servcie();
        if (TextUtils.isEmpty(activity_service)) {
            activity_service = "[]";
        }
        Log.v("zyl", "activity_service:" + activity_service);
        final String temp_activity_servcie = activity_service.substring(1, activity_service.length() - 1).replaceAll(" ", "");
        if (!TextUtils.isEmpty(temp_activity_servcie)) {
            String[] sourceStrArray = temp_activity_servcie.split(",");
            for (int i = 0; i < sourceStrArray.length; i++) {
                if (!tempList.contains(Integer.valueOf(sourceStrArray[i]).intValue())) {
                    int temInt = Integer.valueOf(sourceStrArray[i]).intValue();
                    if(temInt==1||temInt ==2||temInt ==3||temInt ==6||temInt ==8||temInt ==14||temInt ==16||temInt ==20||temInt ==21||temInt ==26||temInt ==27||temInt ==28){
                        tempList.add(Integer.valueOf(sourceStrArray[i]).intValue());//Integer.parseInt(sourceStrArray[i]));
                    }
                }
            }
        }

        if (tempList.contains(1)) {
            iv_wifi.setBackgroundResource(R.drawable.wifi_bigiconorg);
            tv_wifi.setTextColor(resources.getColor(R.color.service_text_color));
        }
        if (tempList.contains(2)) {
            iv_wc.setBackgroundResource(R.drawable.wc_bigiconorg);
            tv_wc.setTextColor(resources.getColor(R.color.service_text_color));
        }
        if (tempList.contains(3)) {
            iv_hot_water.setBackgroundResource(R.drawable.hot2_bigiconorg);
            tv_hot_water.setTextColor(resources.getColor(R.color.service_text_color));
        }
        if (tempList.contains(4)) {

        }
        if (tempList.contains(5)) {
        }
        if (tempList.contains(6)) {
            iv_battery.setBackgroundResource(R.drawable.dian_bigiconorg);
            tv_battery.setTextColor(resources.getColor(R.color.service_text_color));
        }
        if (tempList.contains(7)) {
        }
        if (tempList.contains(8)) {
            iv_express.setBackgroundResource(R.drawable.ex_bigiconorg);
            tv_express.setTextColor(resources.getColor(R.color.service_text_color));
        }
        if (tempList.contains(9)) {

        }
        if (tempList.contains(10)) {

        }
        if (tempList.contains(11)) {

        }
        if (tempList.contains(12)) {

        }
        if (tempList.contains(13)) {

        }
        if (tempList.contains(14)) {
            iv_lock.setBackgroundResource(R.drawable.suo_bigiconorg);
            tv_lock.setTextColor(resources.getColor(R.color.service_text_color));
        }
        if (tempList.contains(15)) {

        }
        if (tempList.contains(16)) {
            iv_dredge.setBackgroundResource(R.drawable.tong_bigiconorg);
            tv_dredge.setTextColor(resources.getColor(R.color.service_text_color));
        }
        if (tempList.contains(17)) {

        }
        if (tempList.contains(18)) {

        }
        if (tempList.contains(19)) {

        }
        if (tempList.contains(20)) {
            iv_maintain.setBackgroundResource(R.drawable.wx_bigiconorg);
            tv_maintain.setTextColor(resources.getColor(R.color.service_text_color));
        }
        if (tempList.contains(21)) {
            iv_tools.setBackgroundResource(R.drawable.tool_bigiconorg);
            tv_tools.setTextColor(resources.getColor(R.color.service_text_color));
        }
        if (tempList.contains(22)) {

        }
        if (tempList.contains(23)) {

        }
        if (tempList.contains(24)) {

        }
        if (tempList.contains(25)) {

        }
        //二手回收
        if (tempList.contains(26)) {
            iv_return.setBackgroundResource(R.drawable.pic_return_red);
            tv_return.setTextColor(resources.getColor(R.color.service_text_color));
        }
        //保险代理
        if (tempList.contains(27)) {
            iv_insurance.setBackgroundResource(R.drawable.pic_baoxian_red);
            tv_insurance.setTextColor(resources.getColor(R.color.service_text_color));
        }
        //其它
        if (tempList.contains(28)) {
            iv_other.setBackgroundResource(R.drawable.pic_other_red);
            tv_other.setTextColor(resources.getColor(R.color.service_text_color));
        }

    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.stores);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        ExitApplication.getInstance().addActivity(this);
        Log.v("zyl", "经度：" + Stores.latitude);
        Log.v("zyl", "纬度：" + Stores.longitude);
        initView();
        initData();
//        updateService();
        EventBus.getDefault().register(this);
        if (db == null) {
            db = new DBHelper_hy(this);
            rb = new recordBean_hy();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }


    //提交资料,更新信息
    private void update() {
        needSubmit = true;
        progressBar = new ProgressDialog(this);
        progressBar.setCancelable(true);
        progressBar.setMessage("提交中...");
        progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressBar.setProgress(0);
        progressBar.setMax(100);
        progressBar.show();

        JSONArray jsonArray = new JSONArray();
        try {
            JSONObject jsonObjectOne = new JSONObject();
            JSONObject jsonObjectTwo = new JSONObject();
            JSONObject jsonObjectThree = new JSONObject();
            JSONObject jsonObjectFour = new JSONObject();

            jsonObjectOne.put("path_id", docIdRoomOne);

            jsonObjectTwo.put("path_id", docIdRoomTwo);

            jsonObjectThree.put("path_id", docIdRoomThree);

            jsonObjectFour.put("path_id", docIdRoomFour);

            jsonArray.put(jsonObjectOne);
            jsonArray.put(jsonObjectTwo);
            jsonArray.put(jsonObjectThree);
            jsonArray.put(jsonObjectFour);
            netRequest.requestSubmitStoresInfo(1, Stores.address, docIdTwo, docIdOne, jsonArray, desc_edit.getText().toString(), s_longitude, s_latitude, tempList.toString());
        } catch (Exception e) {

        }


        Stores.address = site.getText().toString();
        Stores.store_desc = desc_edit.getText().toString();
    }

    @Override
    protected void onDestroy() {
        if (vistabitmap != null)
            vistabitmap.recycle();
        if(locationService != null){
            locationService.stop();
        }
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
    }

    private BDLocationListener mListener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // TODO Auto-generated method stub
            if (null != location
                    && location.getLocType() != BDLocation.TypeServerError) {
                Log.v("zyl","setbaidumapjxdu:"+location.getLatitude());
                Log.v("zyl","setbaidumapjxdu:"+location.getLongitude());
                if("4.9E-324".equals(location.getLatitude()+"")){
                    //showToast("定位失败，请前往手机设置打开定位权限");
                    showPermissionDialog();
                       return;
                }
                s_latitude = location.getLatitude() + "";
                s_longitude = location.getLongitude() + "";
                setbaidumapjxdu(location.getLatitude(),
                        location.getLongitude());
            }

            /*if(location != null){
                if(location.getLocType() == BDLocation.TypeGpsLocation || location.getLocType() == BDLocation.TypeNetWorkLocation
                        || location.getLocType() == BDLocation.TypeOffLineLocation){
                    Log.v("zyl","setbaidumapjxdu:"+location.getLatitude());
                    Log.v("zyl","setbaidumapjxdu:"+location.getLongitude());
                    setbaidumapjxdu(location.getLatitude(),
                            location.getLongitude());
                    showToast("定位成功");
                }else {
                    showToast("定位失败，请前往手机设置打开定位权限");
                }
            }else{
                showToast("定位失败");
            }*/

        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FLAG_CHOOSE_IMG && resultCode == RESULT_OK) {
            if (data != null) {
                Uri uri = data.getData();
                if (uri != null) {
                    //头像的是正方形裁剪，街景是长方形裁剪
                    if (chooseIndex == 0) {
                        CropUtils.startCropActivity(uri, StoresActivity.this, 5, 5);

                    } else {
                        CropUtils.startCropActivity(uri, StoresActivity.this, 2, 1);
                    }

                }
            }
        } else if (requestCode == FLAG_CHOOSE_PHONE && resultCode == RESULT_OK) {
            Log.d("lxp", "=========");
            File f = new File(SettingData.FILE_PIC_SCREENSHOT, localTempImageFileName);
            Uri uri = Uri.fromFile(f);
            if (uri != null) {
                UtilsBitmap.getCompressUri(uri);
                if (chooseIndex == 0) {
                    CropUtils.startCropActivity(uri, StoresActivity.this, 5, 5);
                } else {
                    CropUtils.startCropActivity(uri, StoresActivity.this, 2, 1);
                }
            }
        }


        //拿到裁剪后的图片
        if (requestCode == UCrop.REQUEST_CROP && resultCode == RESULT_OK) {
            if (data != null) {
                final Uri resultUri = UCrop.getOutput(data);
                bitmapBean = UtilsBitmap.addFilePath3(resultUri.getPath(), this);
                tempIndex = chooseIndex;

                if (bitmapBean.getIsBm() != null) {
                    //上传图片
                    netRequest.requestUploadPic(4, bitmapBean.getIsBm());
                }
//                new uploadtask(vistabitmap, tempIndex).start();
            }
        } else if (resultCode == UCrop.RESULT_ERROR) {
            Toast.makeText(StoresActivity.this, "图片剪切失败！", Toast.LENGTH_SHORT)
                    .show();
        }

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //精准定位
            case R.id.rl_zhezhao2:
                locationService.start();
                if(checkLocationPermision()){
                    mMapView.setVisibility(View.VISIBLE);
                    locationService.start();
                }else{
                    showPermissionDialog();
                }
                break;
            //上传头像从
            case R.id.rl_stores_name:
                chooseIndex = 0;
                getPic();
                break;
            //上传街景
            case R.id.vista:
                chooseIndex = 1;
                getPic();
                break;
            //内景1
            case R.id.iv_room_one:
                chooseIndex = 2;
                getPic();
                break;
            //内景2
            case R.id.iv_room_two:
                chooseIndex = 3;
                getPic();
                break;
            //内景3
            case R.id.iv_room_three:
                chooseIndex = 4;
                getPic();
                break;
            //内景4
            case R.id.iv_room_four:
                chooseIndex = 5;
                getPic();
                break;
            case R.id.public_ll_right:
                showDialog();
                break;
        }
    }


    private static final String TAG = "xgp";
    private static final String PACKAGE_URL_SCHEME = "package:";
    public static final int OP_COARSE_LOCATION = 0;//粗略定位(基于网络)
    public static final int OP_FINE_LOCATION = 1;//精确定位(基于GPS和网络)

    /**
     * 检测当前应用是否具有定位权限
     * @return
     */
    public boolean checkLocationPermision() {
       return isAllowed(this, 0);
    }

    /**
     * 是否禁用某项操作
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    public static boolean isAllowed(Context context, int op) {
        Log.d(TAG, "api level: " + Build.VERSION.SDK_INT);
        if (Build.VERSION.SDK_INT < 19) {
            return true;
        }
        Log.d(TAG, "op is " + op);
        String packageName = context.getApplicationContext().getPackageName();
        AppOpsManager aom = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        Class<?>[] types = new Class[]{int.class, int.class, String.class};
        Object[] args = new Object[]{op, Binder.getCallingUid(), packageName};
        try {
            Method method = aom.getClass().getDeclaredMethod("checkOpNoThrow", types);
            Object mode = method.invoke(aom, args);
            Log.d(TAG, "invoke checkOpNoThrow: " + mode);
            if ((mode instanceof Integer) && ((Integer) mode == AppOpsManager.MODE_ALLOWED)) {
                Log.d(TAG, "allowed");
                return true;
            }
        } catch (Exception e) {
            Log.e(TAG, "invoke error: " + e);
            e.printStackTrace();
            return true;

        }
        return false;
    }

    //以下代码可以跳转到应用详情，可以通过应用详情跳转到权限界面(6.0系统测试可用)
    private void startAppDetailActivity(Context context) {
        Intent localIntent = new Intent();
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings","com.android.settings.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
        }
        startActivity(localIntent);
    }

    private  AlertDialog permissionDialog;
    private void showPermissionDialog() {
        /*AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle("尚未开启定位权限")
                .setMessage("获取定位权限将帮助您准确定位门店地址。\n" +
                        "操作路径：设置- 应用- 店东助手- 权限！")
                .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startAppDetailActivity(StoresActivity.this);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        permissionDialog.dismiss();
                    }
                });
        permissionDialog = builder.create();
        permissionDialog.setCanceledOnTouchOutside(true);
        permissionDialog.show();*/

        try{
            if(permissionDialog == null){
                permissionDialog = new AlertDialog.Builder(this).create();
                View contentView = View.inflate(this,R.layout.dialog_check_permision, null);
                TextView tv_ok = (TextView) contentView.findViewById(R.id.tv_ok);
                TextView tv_cancel = (TextView) contentView.findViewById(R.id.tv_cancel);
                tv_ok.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(locationService != null){
                            locationService.stop();
                        }
                        permissionDialog.dismiss();
                        finish();
                        startAppDetailActivity(StoresActivity.this);
                    }
                });
                tv_cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if(locationService != null){
                            locationService.stop();
                        }
                        permissionDialog.dismiss();
                    }
                });
                permissionDialog.setView(contentView);
                permissionDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        if(locationService != null){
                            locationService.stop();
                        }
                    }
                });
            }
            permissionDialog.show();
        }catch (Exception e){
            e.printStackTrace();
        }



    }




    @Override
    public void onAfinalFail() {
        ToastTools.showShort(StoresActivity.this, "请检查本地网络！");
        if (progressBar != null && progressBar.isShowing())
            progressBar.dismiss();
    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        if (requestId == 1) {
            handler.sendEmptyMessage(4);
        } else if (requestId == 2) {
            try {
                JSONObject jsonObject = new JSONObject(result);
                Gson gson = new Gson();
                storesDetailsBean = gson.fromJson(jsonObject.getJSONObject("detail").toString(), StoresDetailsBean.class);
                Map<String, String> map = Utils.getMapForJson(jsonObject.getJSONObject("doc_url").toString());
                storesDetailsBean.setHead_pic_url(map.get(storesDetailsBean.getHead_pic_path()));
                storesDetailsBean.setNeighbor_pic_url(map.get(storesDetailsBean.getNeighbor_pic_path()));
                Log.v("zyl", "用户头像：" + storesDetailsBean.getHead_pic_url());
                Log.v("zyl", "街景：" + storesDetailsBean.getNeighbor_pic_url());
                Log.v("zyl", "内景：" + storesDetailsBean.getStores_thumbnail_path());

                if (!TextUtils.isEmpty(storesDetailsBean.getStores_thumbnail_path())) {
                    JSONArray jsonArray = new JSONArray(storesDetailsBean.getStores_thumbnail_path());//获取街景图片
                    Log.v("zyl", "jsonArray.size:" + jsonArray.length());
                    for (int i = 0; i < jsonArray.length(); i++) {
                        if (storesPicBeansList.get(i) != null) {
                            String path_id = jsonArray.getJSONObject(i).getString("path_id");
                            String path_url = map.get(path_id);
                            Log.v("zyl", "path_url：" + path_url);
                            Log.v("zyl", "path_id：" + path_id);
                            storesPicBeansList.get(i).setUrl(path_url);
                            storesPicBeansList.get(i).setDocId(path_id);
                        }
                    }
                }

                refreshUI();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (requestId == 3) {
            try {
                JSONArray jsonArray = new JSONArray(result);
                if (jsonArray.length() >= 1) {
                    String img = jsonArray.getJSONObject(0).getString("doc_path");
                    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
                    String imuser = preferences.getString("im_user_id", "");
                    if (!TextUtils.isEmpty(img) && !TextUtils.isEmpty(imuser)) {
                        try {
                            rb.saveMember(db, "", imuser, ""
                                    , "", img, "0");
                        } catch (Exception e) {
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (requestId == 4) {

            try {
                JSONObject object = new JSONObject(result);
                String doc_id = object.getString("doc_id");
                Log.v("zyl", "上传图片成功：" + doc_id);
                if (tempIndex == 0) {
                    docIdOne = doc_id;
                    netRequest.requestGetPicUrl(3, docIdOne);
                } else if (tempIndex == 1) {
                    docIdTwo = doc_id;
                } else if (tempIndex == 2) {
                    docIdRoomOne = doc_id;
                } else if (tempIndex == 3) {
                    docIdRoomTwo = doc_id;
                } else if (tempIndex == 4) {
                    docIdRoomThree = doc_id;
                } else if (tempIndex == 5) {
                    docIdRoomFour = doc_id;
                }
                if (!StoresActivity.this.isFinishing()) {
                    handler.sendEmptyMessage(SHOW_PIC);
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 刷新UI
     */

    public void refreshUI() {
        initServiceState();
        String s_pic = storesDetailsBean.getHead_pic_url();
        if (TextUtils.isEmpty(s_pic)) {
            s_pic = "null";
        } else {
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
            String imuser = preferences.getString("im_user_id", "");
            if (!TextUtils.isEmpty(imuser)) {
                try {
                    rb.saveMember(db, "", imuser, ""
                            , "", s_pic, "0");
                } catch (Exception e) {
                }
            }
        }
        //显示头像
        ImageLoader.getInstance().displayImage(s_pic, iv_head, new ImageLoadingListener() {

            @Override
            public void onLoadingStarted(String s, View view) {
            }

            @Override
            public void onLoadingFailed(String s, View view, FailReason failReason) {
                iv_head.setBackgroundResource(R.drawable.pic_icon_default_diandong_head);
            }

            @Override
            public void onLoadingComplete(String s, View view, Bitmap bitmap) {
            }


            @Override
            public void onLoadingCancelled(String s, View view) {
                Log.i("mylog", "ff");
            }
        });
        //显示街景图片
        if (!TextUtils.isEmpty(storesDetailsBean.getNeighbor_pic_url())) {
            ImageLoader.getInstance().displayImage(storesDetailsBean.getNeighbor_pic_url(), imageView, new ImageLoadingListener() {
                @Override
                public void onLoadingStarted(String s, View view) {

                }

                @Override
                public void onLoadingFailed(String s, View view, FailReason failReason) {

                }

                @Override
                public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                    imageView.setVisibility(View.VISIBLE);
                    rl_zhezhao.setVisibility(View.VISIBLE);
                }

                @Override
                public void onLoadingCancelled(String s, View view) {

                }
            });
        }

        if (!TextUtils.isEmpty(storesPicBeansList.get(0).getUrl())) {
            docIdRoomOne = storesPicBeansList.get(0).getDocId();
            ImageLoader.getInstance().displayImage(storesPicBeansList.get(0).getUrl(), iv_room_one);
        }
        if (!TextUtils.isEmpty(storesPicBeansList.get(1).getUrl())) {
            docIdRoomTwo = storesPicBeansList.get(1).getDocId();
            ImageLoader.getInstance().displayImage(storesPicBeansList.get(1).getUrl(), iv_room_two);
        }
        if (!TextUtils.isEmpty(storesPicBeansList.get(2).getUrl())) {
            docIdRoomThree = storesPicBeansList.get(2).getDocId();
            ImageLoader.getInstance().displayImage(storesPicBeansList.get(2).getUrl(), iv_room_three);
        }
        if (!TextUtils.isEmpty(storesPicBeansList.get(3).getUrl())) {
            docIdRoomFour = storesPicBeansList.get(3).getDocId();
            ImageLoader.getInstance().displayImage(storesPicBeansList.get(3).getUrl(), iv_room_four);
        }
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        if (progressBar != null && progressBar.isShowing())
            progressBar.dismiss();
        ToastTools.showShort(StoresActivity.this, msg);
    }


    private void setbaidumapjxdu(double d_latitude, double d_longitude) {

        LatLng cenpt = new LatLng(d_latitude,
                d_longitude);
        MapStatus mMapStatus = new MapStatus.Builder().target(cenpt)
                .zoom(16).build();
        // 定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory
                .newMapStatus(mMapStatus);
        // 改变地图状态
        mBaidumap.setMapStatus(mMapStatusUpdate);
        mBaidumap.setMyLocationEnabled(true);
        mBaidumap.getUiSettings().setZoomGesturesEnabled(false);
        mBaidumap.getUiSettings().setScrollGesturesEnabled(false);
        mBaidumap.clear();
        // 构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option = new MarkerOptions().position(cenpt)
                .icon(bitmap);
        // 在地图上添加Marker，并显示
        mBaidumap.addOverlay(option);
    }


    //上传图片
    private class uploadtask extends Thread {
        Bitmap bitmap;
        int index;//标记是哪个位置的图片

        public uploadtask(Bitmap bitmap, int index) {
            this.bitmap = bitmap;
            temBitmap = bitmap;
            this.index = index;
        }

        public void run() {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            InputStream in = new ByteArrayInputStream(stream.toByteArray());
            DefaultHttpClient httpclient = new DefaultHttpClient();
            try {
                HttpPost httppost = new HttpPost(Stores.http
                        + "/ops-storage/storage/upload");
                MultipartEntity reqEntity = new MultipartEntity();
                reqEntity.addPart("app_token", MainActivity.app_token);
                reqEntity.addPart("category", "oss_community");
                reqEntity.addPart("subffix", "jpg");
                reqEntity.addPart("up_load_file", "pic.jpg", in);
                httppost.setEntity(reqEntity);
                HttpResponse response = null;
                response = httpclient.execute(httppost);
                response.getStatusLine().toString();
                String strResult = EntityUtils.toString(response.getEntity());
                JSONObject obj = new JSONObject(strResult);
                String rsp_code = obj.getString("rsp_code");
                if (rsp_code.equals("succ")) {
                    JSONObject data = obj.getJSONObject("data");
                    String doc_id = data.getString("doc_id");
                    Log.v("zyl", "上传图片成功：" + doc_id);
                    try {
                        if (index == 0) {
                            docIdOne = doc_id;
                            netRequest.requestGetPicUrl(3, docIdOne);
                        } else if (index == 1) {
                            docIdTwo = doc_id;
                        } else if (index == 2) {
                            docIdRoomOne = doc_id;
                        } else if (index == 3) {
                            docIdRoomTwo = doc_id;
                        } else if (index == 4) {
                            docIdRoomThree = doc_id;
                        } else if (index == 5) {
                            docIdRoomFour = doc_id;
                        }
                        if (!StoresActivity.this.isFinishing()) {
                            handler.sendEmptyMessage(SHOW_PIC);
                        }
                    } catch (Exception e) {
                    }
                } else {
                    if (!StoresActivity.this.isFinishing()) {
                        handler.sendEmptyMessage(LOAD_PIC_FAIL);
                    }
                    Log.v("zyl", "上传图片失败");
                }
                in.close();
                stream.close();

            } catch (Exception e) {
                if (!StoresActivity.this.isFinishing()) {
                    handler.sendEmptyMessage(LOAD_PIC_FAIL);
                }
                e.printStackTrace();
            }
        }
    }

    public void getPic() {
        if (dialog != null && dialog.isShowing()) {
            return;
        }
        dialog = new AlertDialog.Builder(StoresActivity.this)
                .setTitle("请选择图片来源")
                .setItems(new String[]{"相册", "相机"},
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                if (which == 0) {
                                    Intent intent = new Intent(
                                            Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                    startActivityForResult(intent,
                                            FLAG_CHOOSE_IMG);
                                } else if (which == 1) {
                                    String status = Environment
                                            .getExternalStorageState();
                                    if (status
                                            .equals(Environment.MEDIA_MOUNTED)) {
                                        try {
                                            localTempImageFileName = "";
                                            localTempImageFileName = String
                                                    .valueOf((new Date())
                                                            .getTime())
                                                    + ".png";
                                            File filePath = SettingData.FILE_PIC_SCREENSHOT;
                                            if (!filePath.exists()) {
                                                filePath.mkdirs();
                                            }
                                            Intent intent = new Intent(
                                                    MediaStore.ACTION_IMAGE_CAPTURE);
                                            File f = new File(filePath,
                                                    localTempImageFileName);
                                            // localTempImgDir和localTempImageFileName是自己定义的名字
                                            Uri u = Uri.fromFile(f);
                                            intent.putExtra(
                                                    MediaStore.Images.Media.ORIENTATION,
                                                    0);
                                            intent.putExtra(
                                                    MediaStore.EXTRA_OUTPUT,
                                                    u);
                                            startActivityForResult(
                                                    intent,
                                                    FLAG_CHOOSE_PHONE);
                                        } catch (ActivityNotFoundException e) {
                                            //
                                        }
                                    }
                                }
                            }
                        }).show();
    }

    public void onEvent(ServiceUpdateBean event) {
        if (event.type == 1) {
            netRequest.requestQueryStoresInfo(2);
//            if (Stores.type_service == null || Stores.type_service.size() == 0) {
//                mRecyclerView.setVisibility(View.GONE);
//            } else {
//                mRecyclerView.setVisibility(View.VISIBLE);
//            }
//            serviceAdapter.setlist(Stores.type_service);
//            serviceAdapter.notifyDataSetChanged();
        }
    }

    Dialog dialog;

    public void showDialog() {
        dialog = new Dialog(this);
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题，否则会影响高度计算，一定要在setContentView之前调用，终于明白有一个设置theme的构造函数的目的了

        Window dialogWindow = dialog.getWindow();

        dialogWindow.setBackgroundDrawableResource(R.color.transparent);
        dialogWindow.setGravity(Gravity.CENTER);

        dialogWindow.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        View dialogView = View.inflate(this,
                R.layout.dialog_stores_erweima, null);
        TextView stores_name = (TextView) dialogView.findViewById(R.id.dia_stores_name);
        stores_name.setText(Stores.stores_name);
        ImageView img = (ImageView) dialogView.findViewById(R.id.dig_ewm);
        Bitmap qrcodeBitmap = null;
        try {
            qrcodeBitmap = EncodingHandler.createQRCode(MainActivity.member_id, 400);
            img.setImageBitmap(qrcodeBitmap);
        } catch (WriterException e) {
            e.printStackTrace();

        }
        ImageView close = (ImageView) dialogView.findViewById(R.id.occlude);
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.setContentView(dialogView);

        dialog.show();
    }
}